define(["jquery","bbcare","comm/datatable/datatable","bld/app/comm/comm","bld/app/drug/drugList.ui"], function($,$bb,$datatable,$bldcomm,$ui) {
    var servers = {}, defaults = {};
    var URL = $bb.baseUrl("blood");

    /**
     * 获取药品大类
     */
    servers.ajaxMedicineBigClass = function(callback) {
        $bb.ajax({
            url: URL + "medicineClass/getAllMedicineClass",
            success: function(data) {
                if (data.success) {
                    callback(data.data);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "获取药品大类出错！");
                }
            }
        });
    }

    /**
     * 获取药品小类
     */
    servers.ajaxMedicineSmallClass = function(params,callback,smallClassId) {
        $bb.ajax({
            url: URL + "medicineInfo/getMedCatalogInfos",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,smallClassId);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "获取药品小类出错！");
                }
            }
        });
    }

    /**
     * 添加药品小类
     */
    servers.ajaxInsertMedcatalog = function(params,callback,datas) {
        $bb.ajax({
            url: URL + "medicineInfo/insertMedcatalog",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,datas);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "添加药品小类出错！");
                }
            }
        });
    }

    /**
     * 修改药品目录小类
     */
    servers.ajaxModifyMedcatalogInfo = function(params,callback,smallClassId) {
        $bb.ajax({
            url: URL + "medicineInfo/modifyMedcatalogInfo",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,smallClassId);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "修改药品目录小类出错！");
                }
            }
        });
    }

    /**
     * 根据类id获取索引号
     */
    servers.getIndexByClassId = function(list,id){
        for (var i = 0; i < list.length; i++) {
            if( list[i].id == id ){
                return i;
            }
        }
    }

    /**
     * 删除药品目录小类
     */
    servers.ajaxRemoveMedcatalogInfo = function(params,callback) {
        $bb.ajax({
            url: URL + "medicineInfo/remMedcatalogInfo",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "删除药品目录小类出错！");
                }
            }
        });
    }

    /**
     * 药品单位查询
     */
    servers.ajaxQueryUnit = function(params,callback,datas) {
        $bb.ajax({
            url: URL + "medUnitDict/queryAllMedUnitDict",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,datas);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "药品单位查询出错！");
                }
            }
        });
    }

    /**
     * 获取药品信息
     */
    servers.ajaxGetMedInfo = function(params,callback,datas) {
        $bb.ajax({
            url: URL + "medicineInfo/getMedSkuInfo",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,datas);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "获取药品信息出错！");
                }
            }
        });
    }

    /**
     * 根据药品名称查询
     */
    servers.ajaxSelect = function(params,callback,className) {
        $bb.ajax({
            url: URL + "medicineInfo/queryMedSkuInfoByName",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,className);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "根据药品名称查询药品出错！");
                }
            }
        });
    }

    /**
     * 添加药品
     */
    servers.ajaxAdd = function(params,callback,datas) {
        $bb.ajax({
            url: URL + "medicineInfo/insertMedSkuInfo",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,datas);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "添加药品出错！");
                }
            }
        });
    }

    /**
     * 修改药品
     */
    servers.ajaxUpdate = function(params,callback,datas) {
        $bb.ajax({
            url: URL + "medicineInfo/modifyMedSkuInfo",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,datas);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "修改药品出错！");
                }
            }
        });
    }

    /**
     * 删除药品
     */
    servers.ajaxDel = function(params,callback,datas){
        $bb.ajax({
            url: URL + "medicineInfo/delMedSkuInfo",
            data: JSON.stringify({
                data: params
            }),
            success: function(data) {
                if (data.success) {
                    callback(data.data,datas);
                } else {
                    $bb.toastShow(data.msg ? data.msg : "删除药品出错！");
                }
            }
        });
    }

    /**
     * 删除药品成功后的回调函数
     */
    var ajaxDelCallBack = function(data,datas){
        var index = $('#medicineBigClass button.active').index();
        $('#medicineBigClass .btn-group button').eq(index).data("smallClassId",datas.parent_id);
        $('#medicineBigClass .btn-group button').eq(index).click();
    }

    /**
     * 确认删除方案分类
     */
    var confirmDelMedSkuInfo = function(data) {
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var params = {
            "oprInfo":{
                "opCode": "2037",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生修改药品【" + data.medicine_name + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "medSkuInfo":{
                "id":data.id
            }
        }
        servers.ajaxDel(params,ajaxDelCallBack,data);
    }
    
    /**
     * 删除药品
     */
    var onDelMedSkuInfo = function() {
        var data = $(this).data("data");
        $bb.toastConfirmShow(confirmDelMedSkuInfo,data,"确认是否删除该药品？");
    }

    /**
     * 请求修改药品接口成功后的回调函数
     */
    var ajaxUpdateCallBack = function(data,datas) {
        $('.' + datas.className).modal('hide');
        var index = servers.getIndexByClassId(defaults.bigClass,datas.bigClassId);
        $('#medicineBigClass .btn-group button').eq(index).data("smallClassId",datas.smallClassId);
        $('#medicineBigClass .btn-group button').eq(index).click();
    }

    /**
     * 修改药品
     */
    servers.onUpdate = function() {
        var datas = $(this).data("datas");
        var medicineName = $.trim($("#medicineName").val());
        var classId = $("#classId").val();
        var catalogId = $("#catalogId").val();
        var frequencyDay = parseInt($("#frequencyDay").val());
        var frequencyTime = parseInt($("#frequencyTime").val());
        var calcuMethod = $("#calcuMethod").val();
        var medicineDose = parseFloat($("#medicineDose").val());
        var medUnitId = $("#medUnitId").val();
        var medicineType = $("#medicineType").val();
        var character = $("#character").val();
        var indication = $("#indication").val();
        var adverseReaction = $("#adverseReaction").val();
        var taboo = $("#taboo").val();
        var considerations = $("#considerations").val();
        var id = $(this).attr("data-id");
        var medicineId = $(this).attr("data-medicineId");
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var obj = {"medicineName":medicineName,"frequencyDay":frequencyDay,"frequencyTime":frequencyTime,"medicineDose":medicineDose};
        if( $bldcomm.validateMedicine(obj) ){
            var params = {
                "oprInfo":{
                    "opCode": "2036",
                    "opType": "3",
                    "opNote": "【" + doctorName + "】医生修改药品【" + medicineName + "】",
                    "channelType": "2",
                    "channelId": channelId
                },
                "medicineInfo":{
                    "medicineName": medicineName,
                    "classId": classId,
                    "catalogId": catalogId,
                    "id": medicineId,
                },
                "medSkuInfo":{
                    "medicineDose": medicineDose,
                    "calcuMethod": calcuMethod,
                    "frequencyDay": frequencyDay,
                    "frequencyTime": frequencyTime,
                    "useUnitId": medUnitId, // 服用剂量单位 使用药物剂量单位
                    "medUnitId": medUnitId,
                    "medicineType": medicineType,
                    "character": character,
                    "indication": indication,
                    "adverseReaction": adverseReaction,
                    "taboo": taboo,
                    "considerations": considerations,
                    "id":id,
                }
            };
            datas.bigClassId = classId;
            datas.smallClassId = catalogId;
            servers.ajaxUpdate(params,ajaxUpdateCallBack,datas);
        }
    }

    /**
     * 获取药品信息成功后的回调函数
     */
    var medDetailCallback = function(data,datas) {
        var tit = datas.type == "01" ? "药品详情页" : datas.type == "02" ? "药品修改页" : "";
        datas.medSkuInfo = data.medSkuInfo;
        datas.className = "drugListModal";
        $bb.modal({
            "className": datas.className,
            "tit": tit,
        }, function() {
            var options = {
                "dom": $("." + datas.className + " .modal-body"),
                "bigClass":defaults.bigClass,
                "smallClass":defaults.smallClass,
                "units":datas.units,
            };
            $.extend(options,data.medSkuInfo);
            if( datas.type == "01" ){
                $.extend(options,{"status":"readonly"});
                $ui.add(options);
                $("." + datas.className).modal("show");
            }else if( datas.type == "02" ){
                $.extend(options,{"status":"update"});
                $ui.add(options);
                $("." + datas.className).modal("show");
                // 修改药品
                $("#update").unbind("click");
                $("#update").data("datas",datas);
                $("#update").click(servers.onUpdate);
            }
        });
    }

    /**
     * 请求单位成功后的回调函数
     */
    var ajaxQueryUnitCallBack = function(data,datas){
        datas.units = data.medUnits;
        var params = {
            "medSkuInfo":{
                "id": datas.data.id
            }
        };
        servers.ajaxGetMedInfo(params,medDetailCallback,datas);
    }

    /**
     * 查看药品详情、修改药品
     */
    var onDetail = function(){
        var datas = $(this).data("datas");
        servers.ajaxQueryUnit({},ajaxQueryUnitCallBack,datas);
    }

    /**
     * 入参
     */
    var inParams = function(args) {
        var classId = $("#medicineBigClass").find('button.active').attr('id') || '';
        var medcatalogId = $("#medicineSmallClass").find('button.active').attr('id') || '';
        var medicineName = $("#datatableForm input[name=medicineName]").val() || '';
        var data = JSON.stringify({
            data: {
                "args": JSON.stringify(args),
                "queryCriteria": {
                    "classId": classId,
                    "medcatalogId": medcatalogId,
                    "medicineName": medicineName,
                }
            }
        });
        return data;
    }
    /**
     * 出参
     */
    var outParams = function(data) {
        return data.rows;
    }
    /**
     * 数据
     */
    var frequency = function(e) {
        return e.frequency_day + '天' + e.frequency_time + '次';
    }
    var calcuMethod = function(e) {
        return e.calcu_method == '01' ? '体表面积' : '体重';
    }
    var medicineType = function(e) {
        return e.medicine_type == '1' ? '正常用药' : '补充用药';
    }
    var columnsData = function() {
        var columnsArr = [
            { "data": 'medicine_name' },
            { "data": 'medicine_dose' },
            { "data": 'unit_name' },
            { "data": frequency },
            { "data": calcuMethod },
            { "data": medicineType },
            { "data": 'catalog_name' },
            {
                "data": null,
                "className": "operate"
            }
        ];
        return columnsArr;
    }

    /**
     * 行绘制回调函数
     */
    var rowCallback = function(row, data, index) {
        var h = '<div class="operate-box"><span class="color-green cursor-pointer drugList-detail">查看</span><span class="color-green cursor-pointer ml8 drugList-update">修改</span><span class="color-green cursor-pointer ml8 drugList-delete">删除</span></div>';
        $('td.operate', row).html(h);
        /* 查看药品详情 */
        $("td.operate .drugList-detail", row).unbind("click");
        $("td.operate .drugList-detail", row).data("datas",{"data":data,"type":"01"}); // 01:代表查看药品详情
        $("td.operate .drugList-detail", row).click(onDetail);
        /* 修改药品信息 */
        $("td.operate .drugList-update", row).unbind("click");
        $("td.operate .drugList-update", row).data("datas",{"data":data,"type":"02"}); // 02:代表修改药品信息
        $("td.operate .drugList-update", row).click(onDetail);
        /* 删除药品 */
        $("td.operate .drugList-delete", row).unbind("click");
        $("td.operate .drugList-delete", row).data("data",data);
        $("td.operate .drugList-delete", row).click(onDelMedSkuInfo);
    }

    /**
     * 初始化完成之后的回调函数
     */
    var initComplete = function(setting, json) {
        var id = $(".layout-bottom table").attr("id");
        $("#" + id).prev("div.row").remove();
        // 搜索 
        $("#searchBtn").click(function() {
            $datatable.table.api().ajax.reload(); // 出发dt的重新加载数据的方法
        });
        // 初始化所有工具提示
        $(function() { $("[data-toggle='tooltip']").tooltip(); });
    }

    /**
     * 获取datatable里的options
     */
    servers.getOptions = function(_defaults) {
        $.extend(defaults,_defaults);
        var sessionId = $bb.getSessionStorage("sessionId");
        var options = {
            "ajax": {
                "url": URL + "medicineInfo/getMedSkusByClassId?sessionId=" + sessionId,
                "data": inParams,
                "dataSrc": outParams,
                error: function(jqXHR, textStatus, errorMsg) {
                    $bb.toastShow("没有查询到药品，请再试一次！", 5000);
                }
            },
            "columns": columnsData(),
            "rowCallback": rowCallback,
            "initComplete": initComplete
        };
        return options;
    }

    return servers;
})